package com.taotao.web.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.Service.RedisService;
import com.taotao.manage.pojo.ItemDesc;
import com.taotao.web.bean.Item;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by zjj on 2018/12/13.
 */
@Service
public class ItemService {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final String REDIS_KEY = "TAOTAO_WEB_ITEM_DETAIL_";
    private static final Integer REDIS_TIME = 60 * 60 * 24;
    @Autowired
    private ApiService apiService;

    @Value("${TAOTAO_MANAGE_URL}")
    private String TAOTAO_MANAGE_URL;
    @Autowired
    private RedisService redisService;

    public Item queryItemById(Long itemId) {
        String key = REDIS_KEY+itemId;
        //命中缓存
        try {
            String cacheData = this.redisService.get(key);
            if(StringUtils.isNotEmpty(cacheData)){
                return MAPPER.readValue(cacheData,Item.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            String url= TAOTAO_MANAGE_URL+ "rest/item/"+itemId;
            String jsonData = this.apiService.doGet(url);
            if(StringUtils.isEmpty(jsonData)){
                return null;
            }
            try {
                this.redisService.set(key,jsonData,REDIS_TIME);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return MAPPER.readValue(jsonData,Item.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ItemDesc queryItemDescByItemId(Long itemId) {
        try {
            String url= TAOTAO_MANAGE_URL+ "rest/item/desc/"+itemId;
            String jsonData = this.apiService.doGet(url);
            if(StringUtils.isEmpty(jsonData)){
                return null;
            }
            return MAPPER.readValue(jsonData,ItemDesc.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
